<template>
	<div class="about">
		<h2>文章评论页面</h2>
		<el-button type="primary" @click="handleAddBtn">添加</el-button>

		<el-dialog
			title="提示"
			:visible.sync="dialogVisible"
			width="80%"
			:before-close="handleClose"
		>
			<span>添加</span>

			<el-form :model="form">
				<template v-if="formStatus === 'add'">
					<el-form-item label="评论作者">
						<el-select v-model="form.userId" placeholder="请选择">
							<el-option
								v-for="(item, index) in authorOptions"
								:key="index"
								:label="item.label"
								:value="item.value"
							>
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="评论文章列表">
						<el-select v-model="form.blogsId" placeholder="请选择">
							<el-option
								v-for="(item, index) in blogsOptions"
								:key="index"
								:label="item.label"
								:value="item.value"
							>
							</el-option>
						</el-select>
					</el-form-item>
				</template>
				<template v-else>
					<el-form-item label="评论作者">
						<el-input
							v-model="form.username"
							disabled
							autocomplete="off"
						></el-input>
					</el-form-item>
				</template>
				<el-form-item label="评论内容">
					<el-input
						v-model="form.content"
						aria-disabled
						autocomplete="off"
					></el-input>
				</el-form-item>
			</el-form>

			<span slot="footer" class="dialog-footer">
				<el-button @click="handleCancelBtn">取 消</el-button>
				<el-button type="primary" @click="handleSureBtn">确 定</el-button>
			</span>
		</el-dialog>

		<hr />
		<el-table :data="commentsList">
			<el-table-column prop="id" label="评论ID"></el-table-column>
			<el-table-column prop="content" label="评论内容"></el-table-column>
			<el-table-column prop="username" label="评论内容"></el-table-column>
			<el-table-column label="评论人">
				<template slot-scope="scope">
					<img
						style="width:50px;height: 50px;"
						:src="scope.row.avatar"
						alt=""
					/>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="评论时间"></el-table-column>

			<el-table-column label="操作">
				<template>
					<el-button size="small" type="primary" style="margin-right:5px;"
						>编辑</el-button
					>
					<el-button size="small" type="danger">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:page-size="opt.size"
			background
			@current-change="handleCurrentChange"
			layout="prev, pager, next"
			:total="total"
		>
		</el-pagination>
	</div>
</template>
<script>
import axios from 'axios'
export default {
	data() {
		return {
			opt: {
				page: 1,
				size: 5
			},
			form: {
				content: '',
				userId: '',
				blogsId: ''
			},
			authorOptions: [],
			blogsOptions: [],
			formStatus: 'add',
			commentsList: [],
			total: 0,
			dialogVisible: false
		}
	},
	watch: {
		'form.userId'(v) {
			console.log(v, 'v')
			this.getBlogsByUserId(v)
		}
	},
	mounted() {
		this.getCommentsList()
		this.getUserList()
	},
	computed: {},
	methods: {
		// 根据选择到的用户身份，去请求当前用户的文章有哪些
		async getBlogsByUserId(userId) {
			const data = await axios.get('/api/searchBlogs', { params: { userId } })
			console.log(data, 'data')
			data.data.data.forEach((item) => {
				this.blogsOptions.push({
					value: item.id,
					label: `我是ID为${item.id}的文章`
				})
			})
			console.log(this.blogsOptions, '--------------------')
		},

		// 请求用户信息
		async getUserList() {
			const data = await axios.get('/api/users')
			console.log('datA:', data)
			// 给作者的下拉框添加数据
			data.data.data.forEach((item, index) => {
				this.authorOptions.push({
					value: item.id,
					label: item.username
				})
			})
			console.log('data:', data)
		},

		// 弹出框关闭
		handleClose() {
			this.dialogVisible = false
		},
		// 添加按钮
		handleAddBtn() {
			this.dialogVisible = true
		},
		// 取消按钮
		handleCancelBtn() {
			this.dialogVisible = false
		},
		// 确定按钮
		handleSureBtn() {
			// userId content blogsId
			console.log(this.form, '我是选中的数据')

			this.addComments(this.form)

			this.dialogVisible = false
		},
		// 添加评论接口
		async addComments(data) {
			const addData = await axios.post('/api/comments', data)
			console.log(addData, 'addData')
		},

		handleCurrentChange(page) {
			this.opt.page = page
			//
			this.getCommentsList()
		},
		async getCommentsList() {
			const comments = await axios.get('/api/comments', {
				params: {
					...this.opt
				}
			})
			const data = comments.data.data.list
			const count = comments.data.data.count
			this.total = count

			this.blogsOptions

			// console.log(count, 'data');
			/**
			 * 1. 第一种方案：直接赋值
			 */
			// for(let i = 0; i < data.length; i++) {
			//    data[i].userInfo = await this.getUserInfo(data[i].userId)
			// }

			/**
			 * 2. 第二种方案：promise.all处理赋值
			 */
			// 需求，这个需求，就是：图片有可能返回失败。一次性做处理 Promise.all
			// 1. Promise.all 处理多个promise实例，一次性请求多个接口，必须都成功，才返回结果
			// 2. Promise.allSetted 方法，也可以处理多个promise实例，成功失败都会返回结构， 而且，可以判断接口返回是否成功
			const arr = []
			for (let i = 0; i < data.length; i++) {
				arr.push(this.getUserInfo(data[i].userId))
			}
			// const allRes = await Promise.all(arr)
			const allRes = await Promise.allSettled(arr)
			for (let key = 0; key < data.length; key++) {
				data[key].username = allRes[key].value.username
				data[key].avatar = allRes[key].value.avatar
			}
			console.log(data, '我是搜有的评论数据')
			this.commentsList = data
		},
		getUserInfo(userId) {
			return new Promise((resolve, reject) => {
				axios.get('/api/getUser', { params: { userId } }).then((res) => {
					// console.log(res, 'res');
					resolve(res.data[0])
				})
			})
		}
	}
}
</script>
